#include "Widget.h"
#include "ui_Widget.h"

bool make_xor(char *nmea_line)
{
//    cout << "nmea_line i: " << nmea_line << endl;
    char xor_chars[] = "0123456789ABCDEF";
    int chcount = 1, len_nmea;
    int Xor = 0;
    len_nmea = strlen(nmea_line);
    while ( (chcount < len_nmea) && ( nmea_line[chcount] != '*') )
        Xor ^= (unsigned short int)(nmea_line[chcount++]);

    if ( nmea_line[chcount] != '*' ) return false;

    nmea_line[chcount + 1] = xor_chars[Xor >> 4];
    nmea_line[chcount + 2] = xor_chars[Xor & 0x0F];

    return true;
}

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}

bool    Widget::calculate(QString cadena)
{
    qDebug() << "cadena : " << cadena;
    string str = cadena.toStdString();
    checksum(str);
    ui->lnResult->setText(QString::fromStdString(str));
    return false;
}

void Widget::on_btnChecksum_clicked()
{
    ui->lblSize->setText("lon = " + QString::number(ui->lnChecksum->text().size()));
    calculate(ui->lnChecksum->text());
}

void    Widget::checksum(string &nmeaString)
{
    char *c = (char *)nmeaString.c_str();
    cout << "i : " << c << endl;
    bool b  = make_xor(c);
    if (b)  nmeaString = c;
    cout << "o : " << nmeaString << endl;
}

void Widget::on_btnSelectAll_clicked()
{
    ui->lnResult->selectAll();
}
